const Log = require('../models/log')

/**
 * par: request:请求的引用， module:模块, bbehavior:行为, str:成功或者失败
 * 产生一条日志
 */
let create_a_log = function(request, module, behavior, str) {
    const request_method = request.method
    const request_url = request._parsedUrl.pathname
    const request_ip = getClientIp(request)
    Log.create({
        user_name: request.user_name,
        user_ip: request_ip,
        request_url: request_url,
        request_method: request_method,
        request_parameter: JSON.stringify(request.body || request.query),
        request_module: module,
        request_behavior: behavior,
        request_status: str || '成功'
    })
}
    

// 根据请求获取请求方的ip地址
const getClientIp = req => {
    return req.headers['x-forwarded-for'] ||
    　　　　req.connection.remoteAddress ||
    　　　　req.socket.remoteAddress ||
    　　　　req.connection.socket.remoteAddress
}

// 判断整数
const zheng_shu = function(num) {
    return num > 0 && /(^[1-9]\d*$)/.test(num)
}
module.exports = {
    getClientIp,
    zheng_shu,
    isInteger,
    create_a_log
}

function isJson(data) {
    var isjson = (typeof(data) == "object" && Object.prototype.toString.call(data).toLowerCase() == "[object object]" && !data.length);
    return isjson;
}

function isString(data) {
    return (typeof data == "string" && data.constructor == String);
}

function isArray(data) {
    return (data instanceof Array);
}

function isInteger(data) {
    if(isString(data))
        return false;
    var regExp =  /^(-|\+)?\d+$/;
    return regExp.test(data);
}
